package com.example;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.scene.control.Alert;

import java.sql.SQLException;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

public class TeacherRecordGradeController implements TeacherSubController {

    @FXML
    private TextField studentUsernameField;
    @FXML
    private ComboBox<String> courseNameComboBox;
    @FXML
    private ComboBox<String> semesterComboBox;
    @FXML
    private TextField scoreField;
    @FXML
    private Button submitButton;

    private Stage primaryStage;
    private TeacherController teacherController;
    private User currentUser;
    private TaughtCourseDAO taughtCourseDAO;
    private GradeDAO gradeDAO;

    @Override
    public void setPrimaryStage(Stage primaryStage) {
        // This sub-controller doesn't need the primary stage directly
    }

    @Override
    public void setTeacherController(TeacherController teacherController) {
        this.teacherController = teacherController;
    }

    @Override
    public void setCurrentUser(User user) {
        this.currentUser = user;
        System.out.println("TeacherRecordGradeController: setCurrentUser called with user: " + (user != null ? user.getUsername() : "null"));
        if (currentUser != null) {
            populateCourseAndSemesterComboBoxes(currentUser.getUsername());
        }
    }

    @FXML
    public void initialize() {
        taughtCourseDAO = new TaughtCourseDAO();
        gradeDAO = new GradeDAO();
        System.out.println("TeacherRecordGradeController initialized.");
    }

    private void populateCourseAndSemesterComboBoxes(String teacherUsername) {
        List<TaughtCourse> taughtCourses = taughtCourseDAO.getTaughtCoursesByTeacherUsername(teacherUsername);
        Set<String> courseNames = new HashSet<>();
        Set<String> semesters = new HashSet<>();

        for (TaughtCourse course : taughtCourses) {
            courseNames.add(course.getCourseName());
            semesters.add(course.getSemester());
        }

        courseNameComboBox.setItems(FXCollections.observableArrayList(courseNames));
        semesterComboBox.setItems(FXCollections.observableArrayList(semesters));
        System.out.println("Populated course and semester combo boxes.");
    }

    @FXML
    private void handleSubmitGrade() {
        String studentUsername = studentUsernameField.getText().trim();
        String courseName = courseNameComboBox.getValue();
        String semester = semesterComboBox.getValue();
        String scoreText = scoreField.getText().trim();

        if (studentUsername.isEmpty() || courseName == null || semester == null || scoreText.isEmpty()) {
            showAlert(Alert.AlertType.WARNING, "输入不完整", "请填写所有字段！");
            return;
        }

        double score;
        try {
            score = Double.parseDouble(scoreText);
            if (score < 0 || score > 100) {
                showAlert(Alert.AlertType.WARNING, "成绩无效", "成绩必须在0到100之间！");
                return;
            }
        } catch (NumberFormatException e) {
            showAlert(Alert.AlertType.WARNING, "成绩格式错误", "请输入有效的数字成绩！");
            return;
        }

        // TODO: Add validation to check if the studentUsername exists in the database
        // TODO: Add validation to check if this teacher actually teaches this course in this semester

        try {
            // Assuming GradeDAO has a method to insert a new grade
            gradeDAO.insertGrade(studentUsername, courseName, score, semester, "未知", null, currentUser.getName());
            showAlert(Alert.AlertType.INFORMATION, "提交成功", "学生成绩录入成功！");
            clearForm();
        } catch (SQLException e) {
            e.printStackTrace();
            showAlert(Alert.AlertType.ERROR, "数据库错误", "录入成绩失败：" + e.getMessage());
        }
    }

    private void clearForm() {
        studentUsernameField.clear();
        courseNameComboBox.getSelectionModel().clearSelection();
        semesterComboBox.getSelectionModel().clearSelection();
        scoreField.clear();
    }

    private void showAlert(Alert.AlertType type, String title, String message) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
} 